package cn.agile4j.rpc.registry;

import cn.agile4j.rpc.constant.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * 实现服务注册
 * 使用 ZooKeeper 客户端可轻松实现服务注册功能
 * Created by Administrator on 2016/8/12.
 */
public class ServiceRegistry {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class) ;

    private CountDownLatch latch = new CountDownLatch(1) ;  //计数的次数 1
    private String registryAddress ;

    public ServiceRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
    }

    public void register(String data) {
        if (StringUtils.isEmpty(data)) {
            ZooKeeper zk = connectServer() ;
            if (zk != null) {
                createNode(zk, data) ;
            }
        }

    }

    private ZooKeeper connectServer() {
        ZooKeeper zk = null ;
        try {
            zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    if (watchedEvent.getState() == Event.KeeperState.SyncConnected)
                        latch.countDown();  // 当前线程调用此方法，则计数减一
                }
            }) ;
            latch.await();  // 调用此方法会一直阻塞当前线程，直到计时器的值为0
        } catch (Exception e) {
            LOGGER.error("",e);
        }
        return zk ;
    }

    private void createNode(ZooKeeper zk, String data) {
        try {
            byte[] bytes = data.getBytes() ;
            String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL) ;
            LOGGER.debug("create zookeeper node ({} => {})", path, data);
        }catch (Exception e) {
            LOGGER.error("",e);
        }
    }
}
